//
//  BaseTableViewController.swift
//  MacStudy
//
//  Created by 30san on 2020/9/24.
//  Copyright © 2020 Dawninest. All rights reserved.
//

import Cocoa

class BaseTableViewController: NSViewController {

    @IBOutlet weak var tableView: NSTableView!
    
    private var dragIndex: Int = 0
    
    private let customTableViewDragType = NSPasteboard.PasteboardType.init("CustomTableViewDragType")
    
    private lazy var dataSources: [String] = {
        var data = Array<String>()
        for index in 0..<20 {
            data.append("cell - \(index)")
        }
        return data
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        // 注册拖拽事件
        tableView.registerForDraggedTypes([customTableViewDragType])
        print("viewDidLoad")
    }
    
}

extension BaseTableViewController: NSTableViewDelegate {
    
    // Drag & Drop
    func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
        print("rowIndexes = \(rowIndexes)")
        // 将拖拽的数据保存到剪切板pboard
        pboard.declareTypes([customTableViewDragType], owner: nil)
        do {
            let data = try? NSKeyedArchiver.archivedData(withRootObject: rowIndexes, requiringSecureCoding: false)
            pboard.setData(data, forType: customTableViewDragType)
            dragIndex = rowIndexes.first!
            print("dragIndex = \(dragIndex)")
        } catch {
//            print("error = \(error.localizedDescription)")
        }
        return true
    }
    
    func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
        return .move
    }
    
    func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
        // 获取到拖拽到指定的位置，然后调整数据
        // 拖拽的cell数据
        print("acceptDrop row = \(row)")
        let oldData = dataSources[dragIndex]
        dataSources.insert(oldData, at: row)
        print("dataSources = \(dataSources)")
        if dragIndex < row {
            dataSources.remove(at: dragIndex)
        }else {
            dataSources.remove(at: dragIndex + 1)
        }
        print("dataSources = \(dataSources)")
        tableView.reloadData()
        return true
    }
}
extension BaseTableViewController: NSTableViewDataSource {
    func numberOfRows(in tableView: NSTableView) -> Int {
        return dataSources.count
    }

    func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
        return dataSources[row]
    }
}
